
package fire.eagle.android;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.*;
import jfireeagle.*;

public class MainActivity extends AbstractActivity 
{
	static final int ID_SETTINGS = Menu.FIRST;
	static final int ID_ABOUT = Menu.FIRST + 1;
	
	private FireEagleClient client;
	private ClientSettings settings;
	private Button btnUpdate;
	private EditText location;
	private CheckBox useGps;
    private LocationManager locManager;
    
	
    public MainActivity()
    {
    	super();
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		
	    super.onCreateOptionsMenu(menu);
	    
	    MenuItem settings = menu.add(Menu.NONE, ID_SETTINGS, Menu.NONE, "Settings");
	    settings.setIcon(android.R.drawable.ic_menu_preferences);
	    settings.setOnMenuItemClickListener(new OnMenuItemClickListener()
	    {

			public boolean onMenuItemClick(MenuItem item)
			{
				Intent i = new Intent();
				i.setClass(getApplicationContext(), EditPreferencesActivity.class);
				MainActivity.this.startActivity(i);
				return true;
			}
	    	
	    });
	    
	    MenuItem about = menu.add(Menu.NONE, Menu.NONE, Menu.NONE, "About");
	    about.setIcon(android.R.drawable.ic_menu_info_details);
	    about.setOnMenuItemClickListener(new OnMenuItemClickListener()
	    {

			public boolean onMenuItemClick(MenuItem item)
			{
				MainActivity.this.startActivity(AboutActivity.INTENT);
				return true;
			}
	    	
	    });
	    
	    return true;
	}

    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        client = AndroidApplication.createFireEagleClient();
        
        settings = client.getClientSettings();

		locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        
        useGps = new CheckBox(this);
        useGps.setText("use GPS");
        useGps.setVisibility(View.GONE);
        useGps.setChecked(false);
        useGps.setOnClickListener(new OnClickListener()
        {

			public void onClick(View v)
			{
				location.setEnabled( ! useGps.isChecked() );
			}
        	
        });
        
        location = new EditText(this);
        location.setText("");
        location.setVisibility(View.GONE);
        
         
        btnUpdate = new Button(this);
        btnUpdate.setText("Update");
        btnUpdate.setVisibility(View.GONE);
        btnUpdate.setOnClickListener(new OnClickListener() 
        {

			public void onClick(View v)
			{
				Runnable runner = new Runnable()
				{
					public void run()
					{
						try
						{
							if (useGps.isChecked())
							{
								android.location.Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
								if (loc != null)
								{
									client.updateLocation(loc.getLatitude(), loc.getLongitude());
								}
								else
								{
									// emulator only:
									// client.updateLocation(45.518872, -122.6793);
								}
							}
							else
							{
								if (location.getText().length() > 0)
								{
									client.updateLocation(location.getText().toString());
								}
							}
						}
						catch (Throwable t)
						{
							t.printStackTrace(); // todo : improve this
						}
					}
				};
				startThread("update loction thread", runner);
			}
        	
        });
        

        if (Util.isCallback(this.getIntent()))
        {
        	
            client.setRequestToken(Preferences.getRequestToken());
            
        	fetchAccessToken();
        	
        	BackgroundService.restart(this);
        	
        }
        else if ( !settings.getUserSpecificToken().isValid() )
        {
				final AlertDialog alert = new AlertDialog.Builder(this).create();
				alert.setMessage("To get started, you will need to login to Yahoo Fire Eagle");
				alert.setButton("Login", new DialogInterface.OnClickListener()
				{

					public void onClick(DialogInterface dialog, int whichButton)
					{
						alert.dismiss();
						
						final String url = client.getUserAuthorizationUrl();

						Log.i(this.getClass().getName(), url);
		    			
			        	Preferences.updateRequestToken(client.getRequestToken());
			        	Preferences.commit();
		    				
						openWebBrowser(url);
						
						MainActivity.this.finish();
						
					}
				});
				alert.show();
				
		}
        
            	
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

       
        if (settings.getUserSpecificToken().isValid())
        {
            layout.addView(location);
            layout.addView(useGps);
            layout.addView(btnUpdate);
            
        	btnUpdate.setVisibility(View.VISIBLE);
        	location.setVisibility(View.VISIBLE);
        	useGps.setVisibility(View.VISIBLE);
        }
        
        
        setContentView(layout);
    }

    protected void fetchAccessToken()
    {
    	
        client.fetchAccessToken();
		
        Preferences.updateUserSpecificAccessToken(client.getClientSettings().getUserSpecificToken());
        Preferences.commit();
        
    }
    
    

    protected void onDestroy()
    {
    	super.onDestroy();

    	if (this.client != null)
    	{
    		this.client.shutdown();
    	}
    }
    
}
